import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
    Row, Col, Card, Form, Input,
    Select, Icon, Button, message, Menu,
    InputNumber, DatePicker, Modal,
    Badge, Divider, Tag, Table
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import { Link } from 'dva/router';
import styles from './ProductCatalog.less';

const FormItem = Form.Item;
const { Option } = Select;
const confirm = Modal.confirm;
const { MonthPicker, RangePicker } = DatePicker;
const { Description } = DescriptionList;
const InputGroup = Input.Group;
/*
  产品管理的产品目录界面
*/

const stateArray = ["关闭", "正常"];
const disStateArray = ["组织新增", "银行合作"];

@connect(({ product, channel }) => ({
    product, channel
}))
@Form.create()
export default class ProductCatalog extends PureComponent {
    state = {
        dataTimeFlag: false,
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        dataTime: [],
        startTime: '',
        endTime: '',
        modal1Visible: false,
        modal2Visible: false,
        productDetails: {},
        productF2CDetails: {},
        isEdit: false,
        ProductDiviList: [],
    };

    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'product/fetchProduct',
            payload: { offset: 0, limit: 10 },
        });

    }

    handleStandardTableChange = (e) => {
        const { dispatch, form } = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const values = {
                offset: (e.current - 1) * e.pageSize,
                limit: e.pageSize,
                ...fieldsValue,
                createTimeBegin: this.state.startTime,
                createTimeEnd: this.state.endTime,
            };
            this.setState({
                formValues: values,
            });
            dispatch({
                type: 'product/fetchProduct',
                payload: values,
            });
        });
        // this.props.dispatch({
        //     type: 'product/fetchProduct',
        //     payload: { offset: (e.current - 1) * e.pageSize, limit: e.pageSize },
        // });
    }

    //详情
    edit = (record) => {
        dispatch({
            type: 'product/queryProductDetails',
            payload: {
                id: record.id
            },
            callback: () => {
                const { product: { productDetails } } = this.props
                this.setState({
                    productDetails,
                    isEdit: false,
                })
                // console.log("userDetails", userDetails)
            }
        });
    }

    //根据id获取产品详情
    handleOpenUpF2CProduct = (record) => {
        const { dispatch } = this.props
        dispatch({
            type: 'product/queryF2CProductDetail',
            payload: {
                productId: record.id
            },
            callback: () => {
                const { product: { productLoading, productF2CDetails, productPage } } = this.props;

                this.setState({
                    productF2CDetails,
                    productId: record.id,
                    modal1Visible: false,
                    modal2Visible: true,
                    isEdit: true,
                })

            }
        })
    }

    //根据id获取产品详情
    handleOpenUpProduct = (record) => {
        const { dispatch } = this.props
        dispatch({
            type: 'product/queryProductDetails',
            payload: {
                id: record.id
            },
            callback: () => {
                const { product: { productDetails } } = this.props
                this.setState({
                    productDetails,
                    modal2Visible: true,
                    isEdit: false,
                })

            }
        })
    }

    handleChangeTime = (dates, dateString) => {
        this.setState({
            dataTime: dateString,
            startTime: dates[0],
            endTime: dates[1],
            dataTimeFlag: false,
        })
    }

    //查询产品
    handleSearch = (e) => {
        // e.preventDefault();
        const { dispatch, form } = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const values = {
                offset: 0,
                limit: 10,
                ...fieldsValue,
                createTimeBegin: this.state.startTime,
                createTimeEnd: this.state.endTime,
            };
            this.setState({
                formValues: values,
            });
            dispatch({
                type: 'product/fetchProduct',
                payload: values,
            });
        });
    };

    //重置
    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            formValues: {},
            dataTimeFlag: true,
        });
        dispatch({
            type: 'product/fetchProduct',
            payload: {
                offset: 0,
                limit: 10,
            }
        });
    };

    //产品开通列表
    handleSearchModal1Visible = () => {
        this.setState({
            modal1Visible: true,
        });
        const { dispatch } = this.props;
        dispatch({
            type: 'product/fetchgetF2CProductList',
            payload: { offset: 0, limit: 10 },
        });

    }

    //产品开通
    handleSearchModa21Visible = () => {
        const { dispatch, location } = this.props;
        const { validateFieldsAndScroll } = this.props.form;
        validateFieldsAndScroll((error, values) => {
            if (!error) {
                this.props.form.resetFields();
                if (this.state.isEdit == true) {
                    dispatch({
                        type: 'product/openProduct',
                        payload: {
                            id: this.state.productId,
                            ...this.state.productF2CDetails,
                            ...values,
                        },
                        callback: () => {
                            const { product: { productResult } } = this.props;
                            if (productResult.code == 200) {
                                message.success("开通成功")
                                dispatch({
                                    type: 'product/fetchProduct',
                                    payload: { offset: 0, limit: 10 },
                                });
                            } else {
                                message.success(productResult.message)
                            }
                        }
                    });
                }
                else {
                    dispatch({
                        type: 'product/updateProductDetails',
                        payload: {
                            id: this.state.productId,
                            ...this.state.productDetails,
                            ...values,
                        },
                        callback: () => {
                            const { product: { productResult } } = this.props;
                            if (productResult.code == 200) {
                                message.success("修改成功")
                                dispatch({
                                    type: 'product/fetchProduct',
                                    payload: { offset: 0, limit: 10 },
                                });
                            } else {
                                message.success(productResult.message)
                            }
                        }
                    });
                }
                this.setState({
                    modal1Visible: false,
                    modal2Visible: false,
                });
            }
        })
    }

    // setModal1Visible() {
    //     this.handleSearchModal1Visible
    //     this.setState({ modal1Visible: true });
    // }

    setModal2Visible = () => {
        this.props.form.resetFields();
        this.setState({ modal2Visible: false });
    }

    handleAdustPrice = (item, e) => {
        item.adjustPrice = Math.round(e.target.value * 100 + 0.0000001) / 100;
        let productF2CDetails = this.state.productF2CDetails;
        productF2CDetails.productDiviList.map((oldItem) => {
            oldItem.id == item.id ? item : oldItem;
        })
        this.setState({ productF2CDetails })
    }

    handleAdustUpdatePrice = (item, e) => {
        item.adjustPrice = Math.round(e.target.value * 100 + 0.0000001) / 100;
        let productDetails = this.state.productDetails;
        productDetails.productDiviList.map((oldItem) => {
            oldItem.id == item.id ? item : oldItem;
        })
        this.setState({ productDetails })
    }

    toggleForm = () => {
        this.setState({
            expandForm: !this.state.expandForm,
        });
    };
    onValidateForm = () => {
        const { dispatch } = this.props;
        dispatch(routerRedux.push(`/product/product-add`));
    };

    renderAdvancedForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={8} sm={24}>
                        <FormItem label="产品名称">
                            {getFieldDecorator('productName')(<Input placeholder="请输入" />)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="产品编号">
                            {getFieldDecorator('productNum')(<Input placeholder="请输入" />)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="使用状态" >
                            {getFieldDecorator('state')(
                                <Select placeholder="请选择" style={{ width: '100%' }}>
                                    <Option value="0">打开</Option>
                                    <Option value="1">关闭</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={8} sm={24}>
                        <FormItem label="创建时间" >
                            {getFieldDecorator('createTime')(
                                <div>
                                    <RangePicker
                                        allowClear={true}
                                        showToday={true}
                                        onChange={this.handleChangeTime}
                                        style={{ width: '100%' }}
                                        value={[
                                            this.state.dataTimeFlag ? null : this.state.startTime,
                                            this.state.dataTimeFlag ? null : this.state.endTime
                                        ]}
                                        showTime={{ hideDisabledOptions: true }}
                                        format="YYYY-MM-DD HH:mm:ss"
                                    />
                                </div>,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                    </Col>
                    <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
                        <Button type="primary" htmlType="submit">查询</Button>
                        <Button type="normal" onClick={this.handleFormReset} style={{ marginLeft: 10 }}>重置</Button>
                        {/* <a style={{ marginLeft: 10 }} onClick={this.toggleForm}>
                            收起 <Icon type="up" />
                        </a>*/}
                    </span>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24} sm={24}>
                        <div className={styles.tableListOperator}>
                            <Button icon="key" type="primary" onClick={this.handleSearchModal1Visible}>
                                开通
                            </Button>
                            {/* <Button icon="plus" onClick={this.onValidateForm}>
                                产品新增
                            </Button> */}
                        </div>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderForm() {
        return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    columns = [{
        title: '产品编号',
        dataIndex: 'productNum',
        key: 'productNum',
    }, {
        title: '产品名称',
        dataIndex: 'productName',
        key: 'productName',
    }, {
        title: '产品额度',
        dataIndex: 'productSize',
        key: 'productSize',
    }, {
        title: '产品类型',
        dataIndex: 'disState',
        key: 'disState',
        render(val) {
            return disStateArray[val];
        },
    }, {
        title: '合作银行',
        dataIndex: 'productBank',
        key: 'productBank',
        title: '合作银行',
        dataIndex: 'bankName',
        key: 'bankName',
    }, {
        title: '使用状态',
        dataIndex: 'state',
        key: 'state',
        render: val =>
            val == '0' ? (
                <Tag color="red">{stateArray[val]}</Tag>
            ) : (
                    <Tag color="green">{stateArray[val]}</Tag>
                ),
        // render(val) {
        //     return <Tag>{stateArray[val]}</Tag>;
        // },
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        // sorter: true,
    }, {
        title: '操作',
        dataIndex: 'id',
        // key: 'id',
        render: (text, record) => (
            //1:打开；0：关闭；
            <Fragment>
                {/* {record.verifyState == '0' ?
                    <Link to={`/product/product-details?id=${record.id}&type=${2}`}>审核</Link>
                    :
                <Link to={`/product/product-details?id=${record.id}&type=${1}`}>详情</Link>
                } */}

                {record.disState == '0' ?
                    <Link to={`/product/product-details?id=${record.id}&type=${1}`}>详情</Link>
                    :
                    <a onClick={() => this.handleOpenUpProduct(record)}>详情</a>
                }

                <Divider type="vertical" />
                {record.state == '0' ?
                    <a onClick={() => this.handleSetState(record, 1)}>打开</a>
                    :
                    <a onClick={() => this.handleSetState(record, 0)}>关闭</a>
                }
            </Fragment>
        ),
    }];

    columns_2 = [{
        title: '产品编号',
        dataIndex: 'productNum',
        key: 'productNum',
        align: 'center'
    }, {
        title: '产品名称',
        dataIndex: 'productName',
        key: 'productName',
        align: 'center'
    }, {
        title: '合作银行',
        dataIndex: 'bankName',
        key: 'bankName',
        align: 'center'
    }, {
        title: '操作',
        dataIndex: 'id',
        align: 'center',
        // key: 'id',
        render: (text, record) => (
            // <Fragment>
            //     <Link to={`/product/product-details?id=${record.id}&type=${3}`}>开通</Link>
            // </Fragment>
            <Fragment>
                <a onClick={() => this.handleOpenUpF2CProduct(record)}>开通</a>
            </Fragment>
        ),
    }];

    handleSetState = (record, newState) => {
        const { dispatch } = this.props;
        confirm({
            title: `你确定要${record.state == '0' ? '打开' : '关闭'}吗?`,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                dispatch({
                    type: 'product/updateProductState',
                    payload: {
                        id: record.id,
                        state: record.state == '0' ? 1 : 0
                    },
                    callback: () => {
                        dispatch({
                            type: 'product/fetchProduct',
                            payload: {
                                offset: 0,
                                limit: 10,
                            },
                        });
                    },
                });
            },
        });
    }

    setModal1VisibleOnCancel = () => {
        this.setState({ modal1Visible: false })
    }

    render() {
        const { dispatch } = this.props;
        const { product: { productList, f2CProductList, productLoading, productDetails, productF2CDetails, productPage, productF2CLoading } } = this.props;
        const { getFieldDecorator } = this.props.form;
        const { isEdit } = this.state;
        // const onValidateOpenForm = () => {
        //     dispatch(routerRedux.push('/product/product-list'));
        // };
        return (
            <PageHeaderLayout title="产品列表">
                {
                    // JSON.stringify(productDetails)
                }
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderAdvancedForm()}
                        </div>
                        {/* <div className={styles.tableListOperator}>
                            <Button icon="key" type="primary" onClick={() => this.setModal1Visible(true)}>
                                开通
                            </Button>

                            <Button icon="plus" onClick={onValidateForm}>
                                产品新增
                            </Button>
                        </div> */}
                        <Table
                            dataSource={productList}
                            columns={this.columns}
                            rowKey="id"
                            pagination={productPage}
                            loading={productLoading}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
                <div>
                    <Modal
                        width="600px"
                        title="产品开通"
                        visible={this.state.modal1Visible}
                        onCancel={this.setModal1VisibleOnCancel}
                        footer={null}
                    >
                        {/* {JSON.stringify(f2CProductList)} */}
                        <div className={styles.tableList}>
                            <Table
                                dataSource={f2CProductList}
                                columns={this.columns_2}
                                rowKey="id"
                                // bordered
                                pagination={productPage}
                                loading={productF2CLoading}
                                onChange={this.handleStandardTableChange}
                            />
                        </div>
                    </Modal>
                </div>
                <div>
                    <Modal
                        width="700px"
                        visible={this.state.modal2Visible}
                        onOk={this.handleSearchModa21Visible}
                        onCancel={this.setModal2Visible}
                        closable={false}
                        title={isEdit ? '产品开通' : '产品详情'}
                    >
                        {/* {JSON.stringify(productDiviList)} */}

                        <Card
                            type="inner"
                            title="➣ 产品信息"
                            loading={productLoading}
                            style={{ marginBottom: 12 }}
                        >
                            {isEdit == true ?
                                <div className={styles.tableList}>
                                    <DescriptionList size="small" col="2">
                                        <Description term="产品名称" style={{ marginBottom: 25 }}>{productF2CDetails && productF2CDetails.productName}</Description>
                                        <Description term="产品种类" style={{ marginBottom: 25 }}>{productF2CDetails && productF2CDetails.productType == '1' ? '分期' : '贷款'}</Description>
                                        <Description term="合作银行" style={{ marginBottom: 25 }}>{productF2CDetails && productF2CDetails.bankName}</Description>
                                        <Description term="生效时间" style={{ marginBottom: 25 }}>
                                            {productF2CDetails && productF2CDetails.beginTime}{productDetails && productF2CDetails.timeValid == 1 ? '~永久' : '~' + productDetails && productF2CDetails.endTime}
                                        </Description>
                                    </DescriptionList>
                                    <DescriptionList size="small" col="1">
                                        <Description term="产品描述">{productF2CDetails && productF2CDetails.productDesc}</Description>
                                    </DescriptionList>
                                </div>
                                :
                                <div className={styles.tableList}>
                                    <DescriptionList size="small" col="2">
                                        <Description term="产品名称" style={{ marginBottom: 20 }}>{productDetails && productDetails.productName}</Description>
                                        <Description term="产品种类" style={{ marginBottom: 20 }}>{productDetails && productDetails.productType == '1' ? '分期' : '贷款'}</Description>
                                        <Description term="合作银行" style={{ marginBottom: 20 }}>{productDetails && productDetails.bankName}</Description>
                                        <Description term="生效时间" style={{ marginBottom: 20 }}>
                                            {productDetails && productDetails.beginTime}{productDetails && productDetails.timeValid == 1 ? '~永久' : '~' + productDetails && productDetails.endTime}
                                        </Description>
                                    </DescriptionList>
                                    <DescriptionList size="small" col="1">
                                        <Description term="产品描述">{productDetails && productDetails.productDesc}</Description>
                                    </DescriptionList>
                                </div>
                            }
                        </Card>

                        <Card
                            type="inner"
                            title="➢ 产品价格"
                        >
                            {isEdit == true ?
                                <div>
                                    {productF2CDetails.productDiviList &&
                                        productF2CDetails.productDiviList.map((item) => {
                                            return (
                                                <Form key={item.id}>
                                                    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                                                        <Col md={3} sm={24}>
                                                            <FormItem label={`${item.nper}期费率`}></FormItem>
                                                        </Col>
                                                        <Col md={9} sm={24}>
                                                            <FormItem>
                                                                <span><Tag color="green">{item.price}%</Tag></span>
                                                            </FormItem>
                                                        </Col>
                                                        <Col md={3} sm={24}>
                                                            <FormItem label="调整费率"></FormItem>
                                                        </Col>
                                                        <Col md={9} sm={24}>
                                                            <FormItem>
                                                                {getFieldDecorator(`adjustPrice[${item.id}]`, {
                                                                    // initialValue: item.adjustPrice,
                                                                })(
                                                                    <Input
                                                                        style={{ width: '60%' }}
                                                                        addonAfter="%"
                                                                        placeholder="请输入"
                                                                        onChange={this.handleAdustPrice.bind(this, item)} />
                                                                )}
                                                            </FormItem>
                                                        </Col>

                                                    </Row>
                                                </Form>
                                            )
                                        })
                                    }
                                    <Form>
                                        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                                            <Col md={2} sm={24}>
                                                <FormItem label="额度"></FormItem>
                                            </Col>
                                            <Col md={9} sm={24}>
                                                <FormItem>
                                                    {getFieldDecorator('productSize', {
                                                        initialValue: productF2CDetails && productF2CDetails.productSize,
                                                    })(
                                                        <Input placeholder="请输入额度" style={{ width: '100%' }} addonAfter="元" />
                                                    )
                                                    }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Form>
                                </div>
                                :
                                <div>
                                    {productDetails.productDiviList &&
                                        productDetails.productDiviList.map((item) => {

                                            return (
                                                <Form key={item.id}>
                                                    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                                                        <Col md={3} sm={24}>
                                                            <FormItem label={`${item.nper}期费率`}></FormItem>
                                                        </Col>
                                                        <Col md={9} sm={24}>
                                                            <FormItem>
                                                                <span><Tag color="green">{item.price}%</Tag></span>
                                                            </FormItem>
                                                        </Col>
                                                        <Col md={3} sm={24}>
                                                            <FormItem label="调整费率"></FormItem>
                                                        </Col>
                                                        <Col md={9} sm={24}>
                                                            <FormItem>
                                                                {getFieldDecorator(`adjustPrice[${item.id}]`, {
                                                                    initialValue: item.adjustPrice,
                                                                })(
                                                                    <Input style={{ width: '60%' }} addonAfter="%" placeholder="请输入" onChange={this.handleAdustUpdatePrice.bind(this, item)} />
                                                                )}
                                                            </FormItem>
                                                        </Col>
                                                    </Row>
                                                </Form>
                                            )
                                        })
                                    }
                                    <Form>
                                        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                                            <Col md={2} sm={24}>
                                                <FormItem label="额度"></FormItem>
                                            </Col>
                                            <Col md={9} sm={24}>
                                                {/* {JSON.stringify(productDetails)} */}
                                                <FormItem>
                                                    {getFieldDecorator('productSize', {
                                                        initialValue: productDetails && productDetails.productSize,
                                                    })(
                                                        <Input placeholder="请输入额度" style={{ width: '100%' }} addonAfter="元" />
                                                    )
                                                    }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Form>
                                </div>
                            }
                        </Card>
                    </Modal>
                </div>
            </PageHeaderLayout >
        );
    }
}